package com.tianxiao.faas.biz.service.corner;

import com.tianxiao.faas.api.param.corner.SearchHotResult;
import com.tianxiao.faas.api.param.corner.SearchHotSaveParam;
import com.tianxiao.faas.common.exception.biz.BizException;
import com.tianxiao.faas.mapper.dao.SearchHotModelMapper;
import com.tianxiao.faas.mapper.model.SearchHotModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchHotService {

    @Resource
    private SearchHotModelMapper searchHotModelMapper;



    public List<SearchHotResult> list(Integer type, Integer count) {
        List<SearchHotModel> searchHotModels = searchHotModelMapper.list(type, count);
        List<SearchHotResult> searchHotResults = new ArrayList<>();
        int i = 1;
        for (SearchHotModel searchHotModel : searchHotModels) {
            SearchHotResult searchHotResult = getSearchHotResult(searchHotModel);
            searchHotResult.setIndex(i);
            searchHotResults.add(searchHotResult);
            i ++;
        }
        return searchHotResults;
    }

    private SearchHotResult getSearchHotResult(SearchHotModel searchHotModel) {
        SearchHotResult searchHotResult = new SearchHotResult();
        searchHotResult.setId(searchHotModel.getId());
        searchHotResult.setName(searchHotModel.getName());

        return searchHotResult;
    }

    public void save(SearchHotSaveParam param) {
        long currentTimeMillis = System.currentTimeMillis();
        SearchHotModel searchHotModel = new SearchHotModel();
        Long id = param.getId();
        searchHotModel.setName(param.getName());
        searchHotModel.setType(param.getType());
        searchHotModel.setSort(param.getIndex());
        searchHotModel.setUpdated(currentTimeMillis);
        if (id == null) {
            searchHotModel.setCreated(currentTimeMillis);
            searchHotModel.setDeleted(0);
            searchHotModelMapper.insertSelective(searchHotModel);
        } else {
            SearchHotModel db = searchHotModelMapper.selectByPrimaryKey(id);
            if (db == null) {
                throw new BizException("更新词条不存在");
            }
            searchHotModel.setId(id);
            searchHotModelMapper.updateByPrimaryKeySelective(searchHotModel);
        }
    }

    public void delete(Long id) {
        long updated = System.currentTimeMillis();
        SearchHotModel searchHotModel = new SearchHotModel();
        searchHotModel.setId(id);
        searchHotModel.setUpdated(updated);
        searchHotModel.setDeleted(1);
        searchHotModelMapper.updateByPrimaryKeySelective(searchHotModel);
    }
}
